import React, { useState, useRef, useEffect, useCallback } from 'react';
import mammoth from 'mammoth';
import * as DiffMatchPatch from 'diff-match-patch';
import MarkdownIt from 'markdown-it';
import { Button, Upload, Modal, message } from "antd";
import axios from 'axios';
import fileIcon from '@/assets/images/file.png';

const ContractComparison = () => {
  const markdown = new MarkdownIt();
  
  const leftDocRef = useRef(null);
  const rightDocRef = useRef(null);
  const reportRef = useRef(null);
  
  const [documentContentLeft, setDocumentContentLeft] = useState('');
  const [documentContentRight, setDocumentContentRight] = useState('');
  const [fileLeft, setFileLeft] = useState(null);
  const [fileRight, setFileRight] = useState(null);
  const [dialogVisible, setDialogVisible] = useState(false);
  const [differenceReport, setDifferenceReport] = useState('');
  const [fileLeftName, setFileLeftName] = useState('');
  const [fileRightName, setFileRightName] = useState('');
  const [isContent, setIsContent] = useState(false);
  const [aiContent, setAiContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [report, setReport] = useState('');
  const [aiText, setAiText] = useState('');
  const [diffStats, setDiffStats] = useState({ add: 0, del: 0 });
  const [syncScrollEnabled, setSyncScrollEnabled] = useState(false); // 同步滚动开关
  const isUserScrollingRef = useRef(false);
  
  const maxRetries = 10;
  const retryInterval = 3000;

  const handleScroll = useCallback((source) => {
    if (!syncScrollEnabled || isUserScrollingRef.current) return;

    isUserScrollingRef.current = true;

    let sourceElement = null;

    switch (source) {
      case 'left':
        sourceElement = leftDocRef.current;
        break;
      case 'right':
        sourceElement = rightDocRef.current;
        break;
      case 'report':
        sourceElement = reportRef.current;
        break;
    }

    if (sourceElement) {
      const scrollTop = sourceElement.scrollTop;
      const scrollLeft = sourceElement.scrollLeft;

      [leftDocRef.current, rightDocRef.current, reportRef.current].forEach(el => {
        if (el && el !== sourceElement) {
          el.scrollTop = scrollTop;
          el.scrollLeft = scrollLeft;
        }
      });
    }

    setTimeout(() => {
      isUserScrollingRef.current = false;
    }, 50);
  }, [syncScrollEnabled]);
  

  useEffect(() => {
    if (!dialogVisible) return;
    
    const leftElement = leftDocRef.current;
    const rightElement = rightDocRef.current;
    const reportElement = reportRef.current;
    
    if (!leftElement || !rightElement || !reportElement) return;
    
    const handleLeftScroll = () => {
      if (!syncScrollEnabled || isScrolling) return;
      syncScroll(leftDocRef, [rightDocRef, reportRef]);
    };
    const handleRightScroll = () => {
      if (!syncScrollEnabled || isScrolling) return;
      syncScroll(rightDocRef, [leftDocRef, reportRef]);
    };
    const handleReportScroll = () => {
      if (!syncScrollEnabled || isScrolling) return;
      syncScroll(reportRef, [leftDocRef, rightDocRef]);
    };
    
    leftElement.addEventListener('scroll', handleLeftScroll);
    rightElement.addEventListener('scroll', handleRightScroll);
    reportElement.addEventListener('scroll', handleReportScroll);
    
    return () => {
      leftElement.removeEventListener('scroll', handleLeftScroll);
      rightElement.removeEventListener('scroll', handleRightScroll);
      reportElement.removeEventListener('scroll', handleReportScroll);
    };
  }, [dialogVisible, syncScrollEnabled]);
  
 
  const extractTextFromHtml = (html) => {
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = html;
    return tempDiv.textContent || tempDiv.innerText || '';
  };
  

  const processHtmlContent = (html) => {
    if (!html.includes('<table') && html.includes('合同名称')) {
    }
    
    html = html.replace(/<table/g, '<table class="contract-table"');
    
    return html;
  };
  
 
  const handleBeforeUploadLeft = (file) => {
    setFileLeft(file);
    setFileLeftName(file.name);
    convertDocxToHtml(file, 'left');
    return false;
  };
  

  const handleBeforeUploadRight = (file) => {
    setFileRight(file);
    setFileRightName(file.name);
    convertDocxToHtml(file, 'right');
    return false; 
  };
  
  
  const removeFile = (side) => {
    if (side === 'left') {
      setFileLeft(null);
      setFileLeftName('');
      setDocumentContentLeft('');
    } else if (side === 'right') {
      setFileRight(null);
      setFileRightName('');
      setDocumentContentRight('');
    }
  };

  const convertDocxToHtml = (file, side) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const arrayBuffer = e.target?.result;
      if (arrayBuffer) {
        // 配置mammoth选项以更好地处理表格
        const options = {
          arrayBuffer,
          styleMap: [
            "p[style-name='Heading 1'] => h1:fresh",
            "p[style-name='Heading 2'] => h2:fresh",
            "p[style-name='Heading 3'] => h3:fresh",
            "b => strong",
            "i => em"
          ],
          includeDefaultStyleMap: true,
          convertImage: mammoth.images.imgElement(function(image) {
            return image.read("base64").then(function(imageBuffer) {
              return {
                src: "data:" + image.contentType + ";base64," + imageBuffer
              };
            });
          })
        };
        
        mammoth.convertToHtml(options)
          .then((result) => {
            console.log('Conversion warnings:', result.messages);
            console.log('Converted HTML:', result.value);
            
            // 检查并处理表格内容
            let processedHtml = processHtmlContent(result.value);
            
            console.log('Processed HTML:', processedHtml);
            
            if (side === 'left') {
              setDocumentContentLeft(processedHtml);
            } else if (side === 'right') {
              setDocumentContentRight(processedHtml);
            }
          })
          .catch((error) => {
            console.error('Error during conversion: ', error);
            message.error('文件转换失败，请检查文件格式');
          });
      }
    };
    reader.readAsArrayBuffer(file);
  };
  

  const startComparison = () => {
    if (fileLeft && fileRight) {
      generateDifferenceReport();
      setDialogVisible(true);
      setIsContent(false);
    }
  };
  

  const generateDifferenceReport = async () => {
    const dmp = new DiffMatchPatch.diff_match_patch();
    
    const textLeft1 = extractTextFromHtml(documentContentLeft);
    const textRight2 = extractTextFromHtml(documentContentRight);
    
    const diffs = dmp.diff_main(documentContentLeft, documentContentRight);
    const diffs2 = dmp.diff_main(textLeft1, textRight2);
    
    dmp.diff_cleanupSemantic(diffs);
    dmp.diff_cleanupSemantic(diffs2);
    
    let diffData = {
      add: [],
      del: []
    };
    
    let aiTextContent = '';
    diffs2.forEach(([op, text]) => {
      if (op === 1) { 
        console.log("新增", text);
        aiTextContent += `<span style="color:green">${escapeHtml(text)}</span>`;
      } else if (op === -1) {
        aiTextContent += `<span style="color:red">${escapeHtml(text)}</span>`;
      } else {
        aiTextContent += escapeHtml(text);
      }
    });
    setAiText(aiTextContent);
    
    let diffReportContent = '';
    diffs.forEach(([op, text]) => {
      if (op === 1) { // Insert
        console.log("新增", text);
        diffReportContent += `<span style="background-color: #d4edda; color: #155724; padding: 2px 4px; border-radius: 3px;">${text}</span>`;
        diffData.add.push(text);
      } else if (op === -1) { // Delete
        console.log("删除", text);
        diffData.del.push(text);
        diffReportContent += `<span style="background-color: #f8d7da; color: #721c24; padding: 2px 4px; border-radius: 3px; text-decoration: line-through;">${text}</span>`;
      } else { // Equal
        diffReportContent += text;
      }
    });
    
    setReport(diffReportContent);
    setDifferenceReport(diffReportContent);
    setDiffStats({
      add: diffData.add.length,
      del: diffData.del.length
    });
    
    console.log('differenceReport', diffReportContent);
    await sendMessage(aiTextContent);
  };
  

  const sendMessage = async (sendText) => {
    try {
      await axios.post(
        "https://api.coze.cn/v3/chat?conversation_id=7474103125985771574", 
        {
          bot_id: "7480470528587808779",
          user_id: "12344",
          stream: false,
          auto_save_history: true,
          additional_messages: [
            {
              role: "user",
              content: '总结这个合同' + sendText,
              content_type: "text"
            }
          ]
        }, 
        {
          headers: {
            Authorization: 'Bearer pat_GOWmZqRKSnRuHlcl01UDHK56nmCPTKMKVJgWljdgxysH3RDU28ujSrPslWFZnyg3',
            "Content-Type": "application/json",
          },
        }
      );
    } catch (error) {
      console.error("Error sending message:", error);
      message.error('AI分析请求失败');
    }
  };
  

  const getMessagesWithRetry = async (retryCount = 0) => {
    setLoading(true);
    try {
      const res = await axios.get(
        "https://api.coze.cn/v1/conversation/message/list?conversation_id=7474103125985771574", 
        {
          params: { order: "ASC" },
          headers: {
            Authorization: 'Bearer pat_GOWmZqRKSnRuHlcl01UDHK56nmCPTKMKVJgWljdgxysH3RDU28ujSrPslWFZnyg3',
            "Content-Type": "application/json",
          },
        }
      );
      
      if (res.data[0].role === 'assistant' && res.data[0].content.length > 6) {
        setLoading(false);
        
        const htmlContent = markdown.render(res.data[0].content);
        setAiContent(htmlContent);
        
        if (isContent) {
          setDifferenceReport(htmlContent);
        } else {
          setDifferenceReport(report);
        }
        
        console.log('aiContent', res.data[0].content);
        return res.data[0].content;
      } else if (retryCount < maxRetries) {
        setTimeout(() => {
          getMessagesWithRetry(retryCount + 1);
        }, retryInterval);
      } else {
        setLoading(false);
        message.error('AI分析超时，请重试');
        return null;
      }
    } catch (error) {
      console.error("Error getting messages:", error);
      setLoading(false);
      message.error('获取AI分析结果失败');
      return null;
    }
  };
  

  const handEnd = async () => {
    setIsContent(!isContent);
    
    if (!isContent) {
      setDifferenceReport('');
      await getMessagesWithRetry();
    } else {
      setDifferenceReport(report);
    }
  };
  

  const escapeHtml = (str) => {
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  };
  

  const recompare = () => {
    setDialogVisible(false);
    setFileLeft(null);
    setFileRight(null);
    setFileLeftName('');
    setFileRightName('');
    setDocumentContentLeft('');
    setDocumentContentRight('');
    setDifferenceReport('');
    setAiContent('');
    setReport('');
    setIsContent(false);
    setSyncScrollEnabled(false); // 重置同步滚动状态
    
    // 重置滚动位置
    setTimeout(() => {
      if (leftDocRef.current) leftDocRef.current.scrollTop = 0;
      if (rightDocRef.current) rightDocRef.current.scrollTop = 0;
      if (reportRef.current) reportRef.current.scrollTop = 0;
    }, 100);
  };
  
  return (
    <div className="square">
      <div className="square-header">
        <div className="title">合同上传 比对差异</div>
        <div>精准比对文档增删改查，高亮定位差异信息</div>
      </div>
      
      <div className="square-body">
        <div className="upload-container">
          <Upload
            className="upload-demo"
            drag
            beforeUpload={handleBeforeUploadLeft}
            showUploadList={false}
            accept=".docx,.doc"
            multiple={false}
          >
            <div className="uplod-title">主板</div>
            <img src={fileIcon} width="60px" height="60px" alt="file icon" />
            <div className="el-upload__text">
              点击或将文件拖拽到这里上传
            </div>
          </Upload>
          {fileLeftName && (
            <div className="uploaded-file-info">
              <span>{fileLeftName}</span>
              <div className="del-text" onClick={() => removeFile('left')}>删除</div>
            </div>
          )}
        </div>
        
        <div className="upload-container">
          <Upload
            className="upload-demo"
            drag
            beforeUpload={handleBeforeUploadRight}
            showUploadList={false}
            accept=".docx,.doc"
            multiple={false}
          >
            <div className="uplod-title">副板</div>
            <img src={fileIcon} width="60px" height="60px" alt="file icon" />
            <div className="el-upload__text">
              点击或将文件拖拽到这里上传
            </div>
          </Upload>
          {fileRightName && (
            <div className="uploaded-file-info">
              <span>{fileRightName}</span>
              <div className="del-text" onClick={() => removeFile('right')}>删除</div>
            </div>
          )}
        </div>
      </div>
      
      <div className="square-footer">
        <Button 
          type="primary" 
          onClick={startComparison} 
          disabled={!fileLeft || !fileRight}
          size="large"
        >
          开始合同比对
        </Button>
      </div>
      
      <Modal
        title="合同对比"
        open={dialogVisible}
        width="1200px"
        onCancel={() => {
          setDialogVisible(false);
          setSyncScrollEnabled(false);
        }}
        footer={[
          <Button key="cancel" onClick={() => {
            setDialogVisible(false);
            setSyncScrollEnabled(false);
          }}>
            取消
          </Button>,
          <Button key="recompare" type="default" onClick={recompare}>
            重新比对
          </Button>,
          <Button 
            key="sync" 
            type={syncScrollEnabled ? "primary" : "default"} 
            onClick={() => {
              const newState = !syncScrollEnabled;
              console.log('切换同步滚动状态:', newState);
              setSyncScrollEnabled(newState);
            }}
          >
            {syncScrollEnabled ? "关闭同步滚动" : "开启同步滚动"}
          </Button>,
          <Button key="toggle" type="primary" onClick={handEnd} loading={loading}>
            {isContent ? '报告差异' : 'AI总结'}
          </Button>
        ]}
        style={{ top: 20 }}
      >
        {/* 头部统计信息 */}
        <div className="header-stats">
          <div className="stats-container">
            <div className="diff-summary">
              <div className="stats-item">
                <span className="stats-label">删除</span>
                <span className="del-count">{diffStats.del}</span>
                <span className="stats-unit">项</span>
              </div>
              <div className="stats-item">
                <span className="stats-label">新增</span>
                <span className="add-count">{diffStats.add}</span>
                <span className="stats-unit">项</span>
              </div>
            </div>
            <div className="color-legend">
              <div className="legend-item">
                <span className="color-box del-color"></span>
                <span className="legend-text">红色表示删除</span>
              </div>
              <div className="legend-item">
                <span className="color-box add-color"></span>
                <span className="legend-text">绿色表示新增</span>
              </div>
            </div>
          </div>
        </div>
        
        <div className="comparison-view">
          <div className="document-comparison">
            <div className="document-left">
              <h4>主板文档</h4>
              <div 
                ref={leftDocRef}
                className="document-content"
                onScroll={() => handleScroll('left')}
                dangerouslySetInnerHTML={{ __html: documentContentLeft }} 
              />
            </div>
            
            <div className="document-right">
              <h4>副板文档</h4>
              <div 
                ref={rightDocRef}
                className="document-content"
                onScroll={() => handleScroll('right')}
                dangerouslySetInnerHTML={{ __html: documentContentRight }} 
              />
            </div>
            
            <div className={`difference-report ${loading ? 'loading' : ''}`}>
              <h4>{isContent ? 'AI总结' : '差异报告'}</h4>
              <div 
                ref={reportRef}
                className="report-content"
                onScroll={() => handleScroll('report')}
                dangerouslySetInnerHTML={{ __html: differenceReport }} 
              />
              {loading && (
                <div className="loading-overlay">
                  <div className="loading-text">AI正在分析中...</div>
                </div>
              )}
            </div>
          </div>
        </div>
      </Modal>
      
      <style jsx>{`
        .square {
          padding: 20px;
        }
        
        .square-header {
          display: flex;
          justify-content: center;
          flex-direction: column;
          font-size: 16px;
          margin: 50px 0;
          text-align: center;
        }
        
        .title {
          margin: 10px 0;
          font-weight: 700;
          font-size: 24px;
        }
        
        .square-body {
          display: flex;
          justify-content: space-between;
          max-width: 1000px;
          margin: 20px auto;
          gap: 40px;
        }
        
        .upload-container {
          flex: 1;
          max-width: 480px;
        }
        
        .uploaded-file-info {
          margin-top: 10px;
          font-size: 14px;  
          height: 20px;
          display: flex;
          gap: 10px;
          justify-content: center;
          color: #606266;
        }
        
        .del-text {
          color: #1890ff;
          cursor: pointer;
        }
        
        .del-text:hover {
          color: #40a9ff;
        }
        
        .square-footer {
          display: flex;
          margin-top: 30px;
          justify-content: center;
        }
        
        .upload-demo {
          width: 100%;
          min-height: 200px;
          display: flex;
          justify-content: center;
          align-items: center;
          text-align: center;
          flex-direction: column;
          border: 2px dashed #d9d9d9;
          border-radius: 6px;
          background: #fafafa;
          transition: border-color 0.3s;
        }
        
        .upload-demo:hover {
          border-color: #1890ff;
        }
        
        .uplod-title {
          font-size: 20px;
          font-weight: 700;
          margin-bottom: 20px;
        }
        
        .el-upload__text {
          color: #666;
          margin-top: 10px;
        }
        
        /* 头部统计信息样式 */
        .header-stats {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          padding: 0 0 16px 0;
        }
        
        .stats-container {
          display: flex;
          gap: 24px;
          align-items: center;
        }
        
        .diff-summary {
          display: flex;
          gap: 24px;
          align-items: center;
        }
        
        .stats-item {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 16px;
          font-weight: 500;
        }
        
        .stats-label {
          color: #666;
          font-size: 14px;
        }
        
        .stats-unit {
          color: #666;
          font-size: 14px;
        }
        
        .del-count {
          color: #f5222d;
          font-size: 20px;
          font-weight: 700;
          min-width: 24px;
          text-align: center;
        }
        
        .add-count {
          color: #52c41a;
          font-size: 20px;
          font-weight: 700;
          min-width: 24px;
          text-align: center;
        }
        
        .color-legend {
          display: flex;
          gap: 16px;
          align-items: center;
        }
        
        .legend-item {
          display: flex;
          align-items: center;
          gap: 6px;
          font-size: 12px;
          color: #666;
        }
        
        .color-box {
          width: 12px;
          height: 12px;
          border-radius: 2px;
          display: inline-block;
        }
        
        .del-color {
          background-color: #f8d7da;
          border: 1px solid #f5c6cb;
        }
        
        .add-color {
          background-color: #d4edda;
          border: 1px solid #c3e6cb;
        }
        
        .legend-text {
          white-space: nowrap;
        }
        
        .comparison-view {
          height: 70vh;
          max-height: 700px;
        }
        
        .document-comparison {
          display: flex;
          width: 100%;
          height: 100%;
          gap: 10px;
        }
        
        .document-left,
        .document-right,
        .difference-report {
          flex: 1;
          height: 100%;
          border: 1px solid #e8e8e8;
          border-radius: 6px;
          overflow: hidden;
          background: #fff;
        }
        
        .document-left h4,
        .document-right h4,
        .difference-report h4 {
          margin: 0;
          padding: 12px 16px;
          background: #f5f5f5;
          border-bottom: 1px solid #e8e8e8;
          font-size: 14px;
          font-weight: 600;
        }
        
        .document-content,
        .report-content {
          height: calc(100% - 45px);
          overflow-y: auto;
          overflow-x: auto;
          padding: 16px;
          font-size: 12px;
          line-height: 1.6;
          scroll-behavior: auto;
          will-change: scroll-position;
          transform: translateZ(0);
        }
        
        /* 自定义滚动条样式 */
        .document-content::-webkit-scrollbar,
        .report-content::-webkit-scrollbar {
          width: 8px;
          height: 8px;
        }
        
        .document-content::-webkit-scrollbar-track,
        .report-content::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 4px;
        }
        
        .document-content::-webkit-scrollbar-thumb,
        .report-content::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 4px;
        }
        
        .document-content::-webkit-scrollbar-thumb:hover,
        .report-content::-webkit-scrollbar-thumb:hover {
          background: #a1a1a1;
        }
        
        .document-content::-webkit-scrollbar-corner,
        .report-content::-webkit-scrollbar-corner {
          background: #f1f1f1;
        }
        
        /* 表格样式 */
        .document-content table,
        .report-content table,
        .contract-table {
          width: 100%;
          border-collapse: collapse;
          margin: 10px 0;
          font-size: 12px;
          display: table !important;
        }
        
        .document-content table td,
        .document-content table th,
        .report-content table td,
        .report-content table th,
        .contract-table td,
        .contract-table th {
          border: 1px solid #000;
          padding: 8px;
          text-align: left;
          vertical-align: middle;
          word-wrap: break-word;
          display: table-cell !important;
        }
        
        .document-content table th,
        .report-content table th,
        .contract-table th {
          background-color: #f5f5f5;
          font-weight: bold;
        }
        
        /* 强制显示表格边框 */
        .document-content table,
        .contract-table {
          border: 1px solid #000 !important;
          table-layout: fixed;
        }
        
        .document-content table td,
        .document-content table th,
        .contract-table td,
        .contract-table th {
          border: 1px solid #000 !important;
        }
        
        .document-content table tr,
        .contract-table tr {
          display: table-row !important;
        }
        
        /* 段落和文本样式 */
        .document-content p,
        .report-content p {
          margin: 8px 0;
          line-height: 1.5;
        }
        
        .document-content h1,
        .document-content h2,
        .document-content h3,
        .document-content h4,
        .report-content h1,
        .report-content h2,
        .report-content h3,
        .report-content h4 {
          margin: 15px 0 10px 0;
          font-weight: bold;
        }
        
        .document-content strong,
        .report-content strong {
          font-weight: bold;
        }
        
        .document-content ol,
        .document-content ul,
        .report-content ol,
        .report-content ul {
          margin: 10px 0;
          padding-left: 20px;
        }
        
        .document-content li,
        .report-content li {
          margin: 5px 0;
        }
        
        .difference-report {
          position: relative;
        }
        
        .loading-overlay {
          position: absolute;
          top: 45px;
          left: 0;
          width: 100%;
          height: calc(100% - 45px);
          background-color: rgba(255, 255, 255, 0.8);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 10;
        }
        
        .loading-text {
          color: #1890ff;
          font-size: 14px;
        }
        
        /* 差异报告样式优化 */
        .report-content span[style*="background-color: #d4edda"] {
          display: inline;
          margin: 0 2px;
        }
        
        .report-content span[style*="background-color: #f8d7da"] {
          display: inline;
          margin: 0 2px;
        }
      `}</style>
    </div>
  );
};

export default ContractComparison;